package com.quanthium.monitor.dingtalk;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import de.codecentric.boot.admin.server.domain.entities.Instance;
import de.codecentric.boot.admin.server.domain.entities.InstanceRepository;
import de.codecentric.boot.admin.server.domain.events.InstanceEvent;
import de.codecentric.boot.admin.server.notify.DingTalkNotifier;

public class CustomDingTalkNotifier extends DingTalkNotifier {
	private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

	public CustomDingTalkNotifier(InstanceRepository repository, RestTemplate restTemplate) {
		super(repository, restTemplate);
	}

	@Override
	protected Object createMessage(InstanceEvent event, Instance instance) {
		Map<String, Object> messageJson = new HashMap<>();
		messageJson.put("msgtype", "text");

		Map<String, Object> content = new HashMap<>();
		content.put("content", buildMessage(event, instance));
		messageJson.put("text", content);

		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		return new HttpEntity<>(messageJson, headers);
	}

	private String buildMessage(InstanceEvent event, Instance instance) {
		StringBuilder sb = new StringBuilder();
		sb.append("服务状态告警\n").append("服务名称 : ").append(instance.getRegistration().getName()).append("\n")
				.append("实例ID : ").append(instance.getId()).append("\n").append("当前状态 : ")
				.append(instance.getStatusInfo().getStatus()).append("\n").append("变更时间 : ")
				.append(LocalDateTime.now().format(formatter)).append("\n").append("服务地址 : ")
				.append(instance.getRegistration().getServiceUrl());
		return sb.toString();
	}
}
